<template>
  <div class="tree-table-container">
    <t-table
      :data="flattenedData"
      :columns="computedColumns"
      :row-key="rowKey"
      :row-class-name="getRowClassName"
      v-bind="$attrs"
      v-on="$listeners"
    >
      <!-- 传递插槽 -->
      <template v-for="(_, slot) in $slots" v-slot:[slot]="scope">
        <slot :name="slot" v-bind="scope" />
      </template>

      <!-- 传递作用域插槽 -->
      <template v-for="(_, slot) in $scopedSlots" v-slot:[slot]="scope">
        <slot :name="slot" v-bind="scope" />
      </template>
    </t-table>
  </div>
</template>

<script>
import { Table as TTable, Button as TButton } from 'tdesign-vue';

export default {
  name: 'TreeTable',
  components: {
    TTable,
    TButton,
  },
  props: {
    data: {
      type: Array,
      default: () => [],
    },
    columns: {
      type: Array,
      default: () => [],
    },
    rowKey: {
      type: String,
      default: 'id',
    },
    // 树形相关配置
    treeConfig: {
      type: Object,
      default: () => ({
        childrenKey: 'children',
        expandedKeys: [],
        defaultExpandAll: false,
        indent: 20,
      }),
    },
    // 哪一列显示展开/收起按钮
    expandColumn: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      expandedKeys: [],
    };
  },
  computed: {
    flattenedData() {
      const result = [];
      this.flattenTreeData(this.data, result, 0);
      return result.filter(item => this.isItemVisible(item));
    },
    computedColumns() {
      return this.columns.map(column => {
        if (column.colKey === this.expandColumn) {
          return {
            ...column,
            cell: (h, { row }) => {
              const indent = row._level * this.treeConfig.indent;
              const hasChildren = row._children && row._children.length > 0;
              const isExpanded = this.expandedKeys.includes(row[this.rowKey]);

              return h('div', {
                style: { paddingLeft: `${indent}px`, display: 'flex', alignItems: 'center' }
              }, [
                hasChildren ? h(TButton, {
                  props: {
                    variant: 'text',
                    size: 'small',
                    theme: 'primary',
                  },
                  on: {
                    click: () => this.toggleExpand(row[this.rowKey])
                  }
                }, isExpanded ? '−' : '+') : h('span', { style: { width: '20px' } }),
                h('span', { style: { marginLeft: '4px' } }, this.getCellValue(row, column))
              ]);
            }
          };
        }
        return column;
      });
    },
  },
  mounted() {
    if (this.treeConfig.defaultExpandAll) {
      this.expandAll();
    } else {
      this.expandedKeys = [...this.treeConfig.expandedKeys];
    }
  },
  methods: {
    // 将树形数据扁平化，添加层级信息
    flattenTreeData(data, result, level, parent = null) {
      data.forEach(item => {
        const flatItem = {
          ...item,
          _level: level,
          _parent: parent,
          _children: item[this.treeConfig.childrenKey] || [],
        };
        result.push(flatItem);

        if (item[this.treeConfig.childrenKey] && item[this.treeConfig.childrenKey].length > 0) {
          this.flattenTreeData(item[this.treeConfig.childrenKey], result, level + 1, flatItem);
        }
      });
    },

    // 判断项目是否可见
    isItemVisible(item) {
      if (item._level === 0) return true;

      let parent = item._parent;
      while (parent) {
        if (!this.expandedKeys.includes(parent[this.rowKey])) {
          return false;
        }
        parent = parent._parent;
      }
      return true;
    },

    // 切换展开/收起
    toggleExpand(key) {
      const index = this.expandedKeys.indexOf(key);
      if (index > -1) {
        this.expandedKeys.splice(index, 1);
      } else {
        this.expandedKeys.push(key);
      }
      this.$emit('expand-change', { key, expanded: index === -1 });
    },

    // 展开所有
    expandAll() {
      const allKeys = [];
      this.getAllKeys(this.data, allKeys);
      this.expandedKeys = allKeys;
    },

    // 收起所有
    collapseAll() {
      this.expandedKeys = [];
    },

    // 获取所有键值
    getAllKeys(data, keys) {
      data.forEach(item => {
        keys.push(item[this.rowKey]);
        if (item[this.treeConfig.childrenKey]) {
          this.getAllKeys(item[this.treeConfig.childrenKey], keys);
        }
      });
    },

    // 获取行样式类名
    getRowClassName({ row }) {
      const classes = [];
      if (row._level > 0) {
        classes.push('tree-table-child-row');
      }
      classes.push(`tree-table-level-${row._level}`);
      return classes.join(' ');
    },

    // 获取单元格值
    getCellValue(row, column) {
      if (column.cell && typeof column.cell === 'function') {
        return column.cell(row, column);
      }
      return row[column.colKey] || '';
    },
  },
};
</script>

<style lang="less" scoped>
.tree-table-container {
  :deep(.tree-table-child-row) {
    .t-table__cell {
      background-color: #fafafa;
    }
  }

  :deep(.tree-table-level-0) {
    .t-table__cell {
      background-color: #fff;
    }
  }

  :deep(.tree-table-level-1) {
    .t-table__cell {
      background-color: #f8f9fa;
    }
  }

  :deep(.tree-table-level-2) {
    .t-table__cell {
      background-color: #f1f3f4;
    }
  }
}
</style>